package com.qf.blog.controller;

import com.qf.blog.listener.ThymeleafListener;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zyt
 * @version 1.0
 */

// 路径跳转的servlet 都通过这个servlet
@WebServlet ("/PageServlet/*")
public class PageServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
            // 1. 通过请求地址获取跳转的页面
            // request.getRequestURI()是获取相对路径
        //replaceAll是替换字符的方法 下面是把相对路径替换成空
       String contextPath = request.getContextPath();
        String path = request.getRequestURI().replaceAll(contextPath+"/PageServlet/","");

        // path.replace 是把.html替换成空
        String page=path.replace(".html","");
        System.out.println("page:"+page);
         // 2. 获取一个上下文对象
        ServletContext servletContext = request.getServletContext();
        // 3 . 获取模板引擎对象
        TemplateEngine templateEngine = ThymeleafListener.getTemplateEngine(servletContext);

        // 4. 创建WebContext对象
        WebContext webContext = new WebContext(request,resp,servletContext);

        // 5 跳转到指定的页面（thymeleaf就会实现渲染）
        templateEngine.process(page,webContext,resp.getWriter());
    }
}
